var app = global.app;
var rootPath = app.rootPath;
var ossApi = require(rootPath + '/pkg/ossClient.js');
var downFile = require(rootPath + '/tool/downFile.js');
var getImageInfo = require(rootPath + '/tool/getImageInfo.js');
var convert = require(rootPath + '/tool/createThumb.js');
var child_process = require('child_process');
var spawn = child_process.spawn;
var models = require('../models/index.js');
var mediaModel = models['media'];
var thumbModel = models['thumb'];
var md5 = require(rootPath + '/tool/md5.js').md5;

var imageType = {
    'jpeg':'jpg',
    'png':'png',
    'gif':'gif',
    'jpg':'jpg'
};

function getFileName(str) {
    return str.split('/').lastItem.toLowerCase();
}

function getBucketName() {
    return 'tuzuan' + Math.floor(Math.random() * 5);
}

function doOSS(q, req, res) {
    q.add(function (resp, next) {
        var Oss = new ossApi.OssClient({
            accessId:'7hc5y16VIrSdP6yl',
            accessKey:'1OHdjbL780e8UJhZUaAJQCjeFRQqxp',
            host:'oss-internal.aliyuncs.com'
        });

        var bucket = getBucketName(),
            fileName = getFileName(resp.data.src);
        var t = Date.now();
        Oss.putObject(bucket, fileName, resp.data.src, {}, function (err) {
            if (err) {
                res.send(err);
                q = null;
            }
            if (resp.path != resp.data.src) {
                spawn('rm', ['-rf', resp.path]);
            }
            spawn('rm', ['-rf', resp.data.src]);
            delete resp.data.src;
            resp.data.uri = 'http://' + bucket + '.oss.aliyuncs.com/' + fileName;
            console.log('oss upload time', Date.now() - t);
            next(resp);
        });
    });
}

function doDown(q, req, res) {
    q.add(function (resp, next) {
        downFile(resp.uri, function (path) {
            resp.path = path;
            if (resp.data) {
                resp.data.src = path;
            }
            next(resp);
        });
    });
}

function doImageInfo(q, req, res) {
    q.add(function (resp, next) {
        getImageInfo(resp.data.src, function (data) {
            resp.data = data;
            next(resp);
        });
    });
}

function doMediaSave(q, req, res) {
    q.add(function (resp, next) {
        var media = new mediaModel();
        resp = resp.data;
        Object.keys(resp).forEach(function (key) {
            media[key] = resp[key];
        });
        media._id = getFileName(resp.uri).split('.')[0];
        media.save(function (err, doc) {
            if (err) {
                res.json(err);
                return;
            }
            next(doc);
        });
    });
}

function doThumbSave(q, req, res) {
    q.add(function (resp, next) {
        var thumb = new thumbModel();
        Object.keys(resp.data).forEach(function (key) {
            thumb[key] = resp.data[key];
        });
        thumb._id = resp.thumbId;
        thumb.save(function (err, doc) {
            if (err) {
                res.json(err);
                return;
            }
            next(doc);
        });
    });
}

function doFileMove(q, req, res) {
    q.add(function (resp, next) {
        var type = imageType[resp.data.type.toLowerCase()];
        if (type !== undefined) {
            var fileName = getFileName(resp.data.src);
            var newSrc = resp.data.src.replace(fileName, fileName.slice(0, 32) + '.' + type);
            var args = [];
            args.push(resp.data.src);
            args.push(newSrc);
            var mv = spawn('mv', args);
            mv.on('exit', function (data) {
                resp.data.src = newSrc;
                next(resp);
            });
        } else {
            res.json('fileType error');
            q = null;
        }
    });
}

function doGetMedia(q, req, res) {
    q.add(function (resp, next) {
        mediaModel.findById(resp, function (err, doc) {
            if (err) {
                res.json(err);
            }
            next(doc);
        });
    });
}

function doConvert(q, req, res) {
    q.add(function (resp, next) {
        convert(resp, function (path) {
            resp.data.src = path;
            next(resp);
        });
    });
}

function doGetThumb(q, req, res) {
    q.add(function (resp, next) {
        thumbModel.findById(resp, function (err, doc) {
            if (err) {
                render(err, req, res);
                q = null;
            } else {
                next(doc);
            }
        });
    });
}

module.exports = {
    doOSS:doOSS,
    doDown:doDown,
    doImageInfo:doImageInfo,
    doMediaSave:doMediaSave,
    doFileMove:doFileMove,
    doGetMedia:doGetMedia,
    doThumbSave:doThumbSave,
    doConvert:doConvert,
    doGetThumb:doGetThumb
};